import tkinter as tk
from tkinter import filedialog, scrolledtext
from tkinter import ttk
from ttkthemes import ThemedTk
import sys
import threading
import queue

import format as format

class ThreadSafeConsole:
    def __init__(self, widget):
        self.widget = widget
        self.queue = queue.Queue()
        self.update_me()

    def write(self, text):
        self.queue.put(text)

    def update_me(self):
        try:
            # 临时启用编辑状态
            self.widget.config(state=tk.NORMAL)
            while True:
                text = self.queue.get_nowait()
                self.widget.insert(tk.END, text)
                self.widget.see(tk.END)
        except queue.Empty:
            # 恢复只读状态
            self.widget.config(state=tk.DISABLED)
        finally:
            # 保持定时刷新
            self.widget.after(100, self.update_me)

    def flush(self):
        pass

def select_folder(var):
    path = filedialog.askdirectory()
    if path:
        var.set(path)
        check_enable()

def check_enable():
    if folder1_var.get() and folder2_var.get():
        execute_btn.state(['!disabled'])
    else:
        execute_btn.state(['disabled'])

def execute_command():
    execute_btn.state(['disabled'])
    output_text.config(state=tk.NORMAL)
    output_text.delete(1.0, tk.END)
    
    sys.stdout = ThreadSafeConsole(output_text)
    
    threading.Thread(target=long_running_task, daemon=True).start()

def long_running_task():
    try:
        folder1 = folder1_var.get()
        folder2 = folder2_var.get()
        machine_type = machine_var.get()
        
        format.process_directory(folder1, folder2, machine_type)
    finally:
        sys.stdout = sys.__stdout__
        root.after(0, execute_btn.state, ['!disabled'])

# 创建主题窗口
root = ThemedTk(theme="arc")
root.title("材料清册合并工具")
root.geometry("800x600")
root.minsize(800, 600)

# 初始化路径变量
folder1_var = tk.StringVar()
folder2_var = tk.StringVar()
machine_var = tk.IntVar(value=0)  # 默认选择锅炉

# 自定义样式
style = ttk.Style()
style.theme_use('arc')
style.configure("TLabel", font=("Segoe UI", 10))
style.configure("TButton", font=("Segoe UI", 10), padding=8)
style.configure("TEntry", font=("Segoe UI", 10), fieldbackground="#f0f0f0")
style.configure("TLabelframe", background="#f8f8f8")
style.configure("TLabelframe.Label", font=("Segoe UI", 10, "bold"), background="#f8f8f8")

# 单选按钮样式
style.configure("TRadiobutton", 
               font=("Segoe UI", 10),
               background="#f8f8f8",
               padding=5)

# 按钮样式
style.map("Accent.TButton",
         foreground=[('pressed', 'white'), ('active', '#0078d4')],
         background=[('pressed', '!disabled', '#005a9e'), ('active', '#0078d4')],
         relief=[('pressed', 'flat'), ('!pressed', 'flat')])

# 主框架
main_frame = ttk.Frame(root, padding=20)
main_frame.pack(fill=tk.BOTH, expand=True)

# 材料清册文件夹区域
frame1 = ttk.Labelframe(main_frame, text="材料清册文件夹", padding=10)
frame1.pack(fill=tk.X, pady=5)

folder1_entry = ttk.Entry(frame1, textvariable=tk.StringVar(), state="readonly")
folder1_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
ttk.Button(frame1, text="选择文件夹", command=lambda: select_folder(folder1_var)).pack(side=tk.RIGHT, padx=5)

# 设备类型选择区域
frame_machine = ttk.Labelframe(main_frame, text="类型", padding=10)
frame_machine.pack(fill=tk.X, pady=5)

# 单选按钮组
radio_frame = ttk.Frame(frame_machine)
radio_frame.pack(side=tk.LEFT, padx=10)

boiler_radio = ttk.Radiobutton(radio_frame, 
                              text="锅炉",
                              variable=machine_var,
                              value=0)
boiler_radio.pack(side=tk.LEFT, padx=10)

turbine_radio = ttk.Radiobutton(radio_frame,
                               text="汽机",
                               variable=machine_var,
                               value=1)
turbine_radio.pack(side=tk.LEFT, padx=10)

# 输入文件夹区域
frame2 = ttk.Labelframe(main_frame, text="输入文件夹", padding=10)
frame2.pack(fill=tk.X, pady=5)

folder2_entry = ttk.Entry(frame2, textvariable=tk.StringVar(), state="readonly")
folder2_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
ttk.Button(frame2, text="选择文件夹", command=lambda: select_folder(folder2_var)).pack(side=tk.RIGHT, padx=5)

# 执行按钮区域
btn_frame = ttk.Frame(main_frame)
btn_frame.pack(fill=tk.X, pady=10)

execute_btn = ttk.Button(btn_frame, text="执行操作", style="Accent.TButton", command=execute_command, state=tk.DISABLED)
execute_btn.pack(side=tk.TOP, pady=5, ipadx=20, ipady=5)

# 输出日志区域
log_frame = ttk.Labelframe(main_frame, text="执行日志", padding=10)
log_frame.pack(fill=tk.BOTH, expand=True, pady=10)

output_text = scrolledtext.ScrolledText(
    log_frame,
    wrap=tk.WORD,
    state=tk.DISABLED,
    bg="#f0f0f0",
    bd=0,
    highlightthickness=1,
    highlightbackground="#d0d0d0",
    font=("Segoe UI", 10)
)
output_text.pack(fill=tk.BOTH, expand=True)

# 绑定路径变量到Entry组件
folder1_entry.config(textvariable=folder1_var)
folder2_entry.config(textvariable=folder2_var)

# 添加悬停效果
style.map("TButton",
         foreground=[('pressed', 'white'), ('active', '#66b3ff')],
         background=[('pressed', '!disabled', '#0059b3'), ('active', '#004d99')])

# 运行主循环
root.mainloop()